//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.szboanda.platform.common.component.pageoffice.controller;

import com.github.pagehelper.PageInfo;
import com.szboanda.platform.common.base.BaseController;
import com.szboanda.platform.common.base.BaseException;
import com.szboanda.platform.common.component.pageoffice.exceptions.PageOfficeException;
import com.szboanda.platform.common.component.pageoffice.service.IPageOfficeNewService;
import com.szboanda.platform.common.component.pageoffice.service.IPageOfficeService;
import com.szboanda.platform.common.utils.LoggerUtil;
import com.szboanda.platform.common.utils.MapUtils;
import com.szboanda.platform.common.utils.StringUtils;
import com.szboanda.platform.common.utils.Toolkit;
import com.szboanda.platform.common.utils.simplesso.model.TokenVO;
import com.szboanda.platform.common.utils.simplesso.service.ITokenService;
import com.szboanda.platform.file.service.IFileService;
import com.szboanda.platform.rms.user.mode.UserVO;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.PageOfficeLink;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Controller
@RequestMapping({"/platform/common/pageofficecontroller"})
public class PageofficeController extends BaseController {
    @Autowired
    private IPageOfficeService officeService;
    @Autowired
    private IPageOfficeNewService officeServiceNew;
    @Autowired
    private IFileService fileService;
    @Autowired
    private ITokenService tokenService;

    public PageofficeController() {
    }

    @RequestMapping({"/testview"})
    public String testView() {
        return "platform/common/component/pageoffice/pageofficetest";
    }

    @RequestMapping({"/tofilehistory/{wjid}"})
    public String toFileHistory(@PathVariable("wjid") String wjid) {
        this.getRequest().setAttribute("wjid", wjid);
        return "platform/common/component/pageoffice/filehistory";
    }

    @RequestMapping(
            value = {"/displaySignPic/{userId}"},
            method = {RequestMethod.GET}
    )
    public void displaySignPic(HttpServletRequest request, HttpServletResponse response, @PathVariable("userId") String userId) throws Exception {
        if (StringUtils.isEmpty(userId)) {
            userId = this.getYhid();
        }

        Map<String, Object> fileInfo = this.officeService.getFileByUserId(userId);
        String wjid = MapUtils.getString(fileInfo, "WJID");
        if (null != fileInfo) {
            String fileName = fileInfo.get("WJMC").toString();
            this.getResponse().setContentType("application/octet-stream");
            this.getResponse().setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            this.outPutFileStream(wjid);
        } else {
            throw new BaseException("用户" + userId + "没有上传相关签名照");
        }
    }

    @RequestMapping(
            value = {"/openpageoffice/{wjid}"},
            method = {RequestMethod.GET}
    )
    public void openPageOffice(HttpServletRequest request, HttpServletResponse response, @PathVariable("wjid") String wjid) throws Exception {
        Map<String, Object> fileInfo = this.fileService.getFileInfo(wjid);
        String fileName = MapUtils.getString(fileInfo, "WJMC");
        fileName = new String(fileName.getBytes("utf-8"), "utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentType("application/octet-stream");
        this.outPutFileStream(wjid);
    }

    private void outPutFileStream(String id) throws Exception {
        InputStream is = this.fileService.getFileInputStream(id);
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(this.getResponse().getOutputStream());
        byte[] b = new byte[4096];

        int c;
        while((c = bis.read(b)) != -1) {
            bos.write(b, 0, c);
        }

        bos.flush();
        bos.close();
        bis.close();
        is.close();
    }

    @RequestMapping({"/pageofficepreview"})
    public String pageOfficePreview(HttpServletRequest request) throws Exception {
        this.setToken();
        UserVO user = this.getCurrUser();
        Map<String, Object> signatureFile = this.officeService.getFileByUserId(this.getYhid());
        if (null != signatureFile) {
            request.setAttribute("signatureId", signatureFile.get("WJID"));
        }

        String templateId = request.getParameter("templateId");
        String ywsjId = request.getParameter("ywsjId");
        String wjid = request.getParameter("wjid");
        if (StringUtils.isNotEmpty(templateId) && StringUtils.isNotEmpty(ywsjId)) {
            String fileName = (String)this.getSession().getAttribute("fileName");
            Map<String, Object> fileMap = this.officeService.getOfficeFileInfo(templateId, ywsjId, fileName, user);

            //每次点击公文套红，都会生成一个新的文件。 处理方式：生成新的文件后，我们把之前的文件，从附件表修改信息，并添加到附件历史表中，并把物理文件移动至相应的文件夹
            //暂时注释了每次点击套红时生成一个新的文件


            request.setAttribute("wjid", fileMap.get("WJID"));
            request.setAttribute("wjlx", fileMap.get("WJLX"));
        } else if (StringUtils.isNotEmpty(wjid)) {
            Map<String, Object> fileMap = this.fileService.getFileInfo(wjid);
            if (null == fileMap) {
                LoggerUtil.error(this.getClass(), "根据wjid=" + wjid + "获取文档为空");
                throw new BaseException("根据wjid=" + wjid + "获取文档为空");
            }

            request.setAttribute("wjid", wjid);
            request.setAttribute("wjlx", fileMap.get("WJLX"));
        }

        //查询公文类型（发文套红的模板类型）

        List<Map<String,Object>> gwlxList = officeServiceNew.getGwlx();
        request.setAttribute("gwlxList", gwlxList);
        return "platform/common/component/pageoffice/filepreview";
    }

    @RequestMapping(
            value = {"/updateofficefile"},
            method = {RequestMethod.POST}
    )
    public String updateOfficeFile(HttpServletRequest request, HttpServletResponse response) throws PageOfficeException {
        FileSaver fileSaver = new FileSaver(request, response);
        this.officeService.updateFile(fileSaver);
        request.setAttribute("fileSaver", fileSaver);
        return "/platform/common/component/pageoffice/officereturn";
    }

    @RequestMapping(
            value = {"/getfilehistorylist"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public PageInfo<Map<String, Object>> getFileHistoryList(@RequestBody Map<String, Object> data) throws Exception {
        int pageNum = this.getPageNum(data);
        int pageSize = this.getPageSize(data);
        return this.officeService.getFileHistoryList(pageNum, pageSize, data);
    }

    @RequestMapping(
            value = {"/getofficeopenurl"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public Map<String, Object> getOfficeOpenUrl(@RequestBody Map<String, Object> data) throws Exception {
        String ssoParams = this.getSSoParam();
        String url = "/platform/common/pageofficecontroller/pageofficepreview?ssoParams=" + ssoParams;
        String config = "left=20px;top=10px;width=1200px;height=800px;";
        if (null != data.get("width")) {
            config = config.replace("1200px", data.get("width").toString());
        }

        if (null != data.get("height")) {
            config = config.replace("800px", data.get("height").toString());
        }

        data.put("link", PageOfficeLink.openWindow(this.getRequest(), url, config));
        return data;
    }

    @RequestMapping(
            value = {"/setsessionvalue"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public Map<String, Object> setSessionValue(@RequestBody Map<String, Object> data) throws Exception {
        Iterator var2 = data.entrySet().iterator();

        while(var2.hasNext()) {
            Entry<String, Object> entry = (Entry)var2.next();
            this.getSession().setAttribute((String)entry.getKey(), entry.getValue());
        }

        return this.getSuccessMap();
    }

    private String getSSoParam() {
        TokenVO tokenVO = new TokenVO();
        tokenVO.setSessionToken(Toolkit.getUUID());
        tokenVO.setCreateTime(new Date());
        tokenVO.setUserId(this.getYhid());
        tokenVO.setTokenType("pageoffice");
        tokenVO.setTimeOut(600000);
        this.tokenService.saveToken(tokenVO);
        return tokenVO.getSessionToken() + ";" + tokenVO.getUserId() + ";" + tokenVO.getTokenType();
    }

    private String getYhid() {
        String yhid = "";
        UserVO user = this.getCurrUser();
        if (user != null) {
            yhid = user.getYhid();
        }

        return yhid;
    }
}
